import React, {useEffect, useState} from "react";
import {Button, Card, Cascader, Col, DatePicker, Form, Input, Modal, Row, Select, Table, TableProps} from "antd";
import {Candidate} from "@/types/resp/candidate";
import { AreaOption } from "@/types/areaOption";
import areas from "@/locales/area.json";
import { ApplicationRecord } from "@/types/resp/applicationRecord";
import candidateApi from "@/api/candidateApi";
import { Result } from "@/types/result";
import { Education } from "@/types/resp/education";
import { Page } from "@/types/page";
import educationApi from "@/api/educationApi";
import { EducationQueryForm } from "@/types/req/educationQueryForm";
import { WorkExperience } from "@/types/resp/workExperience";
import { WorkExperienceQueryForm } from "@/types/req/workExperienceQueryForm";
import workExperienceApi from "@/api/workExperienceApi";
import { SkillCertificate } from "@/types/resp/skillCertificate";
import skillCertificateApi from "@/api/skillCertificateApi";
import { SkillCertificateQueryForm } from "@/types/req/skillCertificateQueryForm";
import { TrainingRecord } from "@/types/resp/trainingRecord";
import trainingRecordApi from "@/api/trainingRecordApi";
import { TrainingRecordQueryForm } from "@/types/req/trainingRecordQueryForm";

interface CandidateViewAllProps {
  visible: boolean;
  viewRow: object;
  onCloseCandidateViewAll: () => void;
}

const CandidateView: React.FC<CandidateViewAllProps> = ({visible, viewRow, onCloseCandidateViewAll}) => {

  const [applicationRecordForm] = Form.useForm<ApplicationRecord>();
  const [candidateForm] = Form.useForm<Candidate>();

  const provinceCityAreaOptions: AreaOption[] = areas.provinces

  const onBack = () => {
    onCloseCandidateViewAll()
  };

  useEffect(() => {
    if (!visible) {
      return
    }
    if (viewRow) {
      applicationRecordForm.setFieldsValue(viewRow);

      if ('candidateId' in viewRow) {
        initCandidateFormById(viewRow.candidateId as number)
        onSearchEducation(viewRow.candidateId as number)
        onSearchWorkExperience(viewRow.candidateId as number)
        onSearchSkillCertificate(viewRow.candidateId as number)
        onSearchTrainingRecord(viewRow.candidateId as number)
      }

    }
  }, [viewRow]);
  
  const initCandidateFormById = async (id: number) => {
    const resp: Result<Candidate> = await candidateApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      const provinceCityArea2 = []
      if (resp.data.province) {
        provinceCityArea2.push(resp.data.province)
      }
      if (resp.data.city) {
        provinceCityArea2.push(resp.data.city)
      }
      if (resp.data.area) {
        provinceCityArea2.push(resp.data.area)
      }
      candidateForm.setFieldsValue({...resp.data, provinceCityArea: provinceCityArea2});
    }
  }

  
  const [educationData, setEducationData] = useState<Education[]>([]);
  const onSearchEducation = async (candidateId: number) => {
    try {
      const resp: Result<Page<Education>> = await educationApi.find({
        candidateId: candidateId
      } as EducationQueryForm)
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Education> = resp.data
          if (page && page.list.length > 0) {
            setEducationData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };
  const educationColumns: TableProps<Education>['columns'] = [
    {title: '应聘者姓名', dataIndex: 'candidateName', key: 'candidateName'},
    {title: '学校名称', dataIndex: 'schoolName', key: 'schoolName'},
    {title: '学历', key: 'degree', render: (_, record) => (
        <span>
        {(function () {
          if (record.degree === 10) return '初中';
          else if (record.degree === 20) return '高中';
          else if (record.degree === 30) return '本科';
          else if (record.degree === 40) return '硕士研究生';
          else if (record.degree === 50) return '博士研究生';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '开始日期', key: 'startDate', render: (_, record) => (
      <div>{record.startDate ? record.startDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '结束日期', key: 'endDate', render: (_, record) => (
      <div>{record.endDate ? record.endDate.format('YYYY-MM-DD') : ''}</div>
    )}
  ];

  
  const [workExperienceData, setWorkExperienceData] = useState<WorkExperience[]>([]);
  const onSearchWorkExperience = async (candidateId: number) => {
    try {
      const resp: Result<Page<WorkExperience>> = await workExperienceApi.find({
        candidateId: candidateId
      } as WorkExperienceQueryForm)
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<WorkExperience> = resp.data
          if (page && page.list.length > 0) {
            setWorkExperienceData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };
  const workExperienceColumns: TableProps<WorkExperience>['columns'] = [
    {title: '应聘者姓名', dataIndex: 'candidateName', key: 'candidateName'},
    {title: '公司名称', dataIndex: 'company', key: 'company'},
    {title: '岗位', dataIndex: 'position', key: 'position'},
    {title: '开始日期', key: 'startDate', render: (_, record) => (
      <div>{record.startDate ? record.startDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '结束日期', key: 'endDate', render: (_, record) => (
      <div>{record.endDate ? record.endDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '岗位职责', dataIndex: 'responsibilities', key: 'responsibilities', ellipsis: true}
  ];

  

  const [skillCertificateData, setSkillCertificateData] = useState<SkillCertificate[]>([]);
  const onSearchSkillCertificate = async (candidateId: number) => {
    try {
      const resp: Result<Page<SkillCertificate>> = await skillCertificateApi.find({
        candidateId: candidateId
      } as SkillCertificateQueryForm)
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<SkillCertificate> = resp.data
          if (page && page.list.length > 0) {
            setSkillCertificateData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const skillCertificateColumns: TableProps<SkillCertificate>['columns'] = [
    {title: '应聘者姓名', dataIndex: 'candidateName', key: 'candidateName'},
    {title: '证书名称', dataIndex: 'certificateName', key: 'certificateName'},
    {title: '颁发机构', dataIndex: 'issuingAuthority', key: 'issuingAuthority'},
    {title: '颁发时间', key: 'issueDate', render: (_, record) => (
      <div>{record.issueDate ? record.issueDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '到期日期', key: 'expiryDate', render: (_, record) => (
      <div>{record.expiryDate ? record.expiryDate.format('YYYY-MM-DD') : ''}</div>
    )},
  ];

  
  const [trainingRecordData, setTrainingRecordData] = useState<TrainingRecord[]>([]);
  const onSearchTrainingRecord = async (candidateId: number) => {
    try {
      const resp: Result<Page<TrainingRecord>> = await trainingRecordApi.find({
        candidateId: candidateId
      } as TrainingRecordQueryForm)
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<TrainingRecord> = resp.data
          if (page && page.list.length > 0) {
            setTrainingRecordData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const trainingRecordColumns: TableProps<TrainingRecord>['columns'] = [
    {title: '应聘者姓名', dataIndex: 'candidateName', key: 'candidateName'},
    {title: '培训名称', dataIndex: 'trainingName', key: 'trainingName'},
    {title: '培训日期', key: 'trainingDate', render: (_, record) => (
      <div>{record.trainingDate ? record.trainingDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '培训时长', dataIndex: 'durationHours', key: 'durationHours'},
    {title: '培训供应商', dataIndex: 'provider', key: 'provider'},
    {title: '培训内容', dataIndex: 'trainingDescription', key: 'trainingDescription', ellipsis: true}
  ];

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onBack}>关闭</Button>
    </div>
  );

  const candidateViewAllStyle = {
    height: '70vh',
    width: '100%',
    margin: '0 auto',
    overflow: 'auto'
  }

  return (
    <Modal title={"应聘者基本信息详情"} open={visible} onCancel={onCloseCandidateViewAll}
        width={'var(--modal-width)'} footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <div style={candidateViewAllStyle}>
        <Card title="招聘岗位信息">
        <Form form={applicationRecordForm} name="applicationRecordForm" labelCol={{span: 6}}>
          <Row gutter={10}>
            <Col span={11}>
              <Form.Item name="enterpriseName" label="企业名称">
                <Input disabled/>
              </Form.Item>
            </Col>
            <Col span={11}>
              <Form.Item name="jobDescriptionName" label="招聘岗位名称" >
                <Input disabled/>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        </Card>
        <Card title="基本信息">
          <Form form={candidateForm} labelCol={{span: 6}} disabled={true}>
            <Row gutter={10}>
              <Col span={11}>
                <Form.Item name="username" label="用户名">
                  <Input/>
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item name="name" label="姓名">
                  <Input/>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={10}>
              <Col span={11}>
                <Form.Item name="password" label="密码">
                  <Input/>
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item name="gender" label="性别">
                  <Select placeholder="请选择性别" options={[
                    { value: 1, label: <span>男</span> },
                    { value: 2, label: <span>女</span> }
                  ]} />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={10}>
              <Col span={11}>
                <Form.Item name="birthDate" label="出生日期">
                  <DatePicker/>
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item name="contactPhone" label="联系电话">
                  <Input/>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={10}>
              <Col span={11}>
                <Form.Item name="email" label="邮箱">
                  <Input/>
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item name="provinceCityArea" label="省/市/区">
                  <Cascader options={provinceCityAreaOptions} fieldNames={{ label: "name", value: "code" }}/>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={10}>
              <Col span={11}>
                <Form.Item name="address" label="家庭地址">
                  <Input/>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card title="教育经历">
          <Table<Education> columns={educationColumns} dataSource={educationData} size="small" rowKey={record => record.id} style={{marginTop: 'var(--container-margin)'}} pagination={false} />
        </Card>
        <Card title="工作经历">
          <Table<WorkExperience> columns={workExperienceColumns} dataSource={workExperienceData} size="small" rowKey={record => record.id} style={{marginTop: 'var(--container-margin)'}} pagination={false} />
        </Card>
        <Card title="技能证书">
          <Table<SkillCertificate> columns={skillCertificateColumns} dataSource={skillCertificateData} size="small" rowKey={record => record.id} style={{marginTop: 'var(--container-margin)'}} pagination={false} />
        </Card>
        <Card title="培训记录">
          <Table<TrainingRecord> columns={trainingRecordColumns} dataSource={trainingRecordData} size="small" rowKey={record => record.id} style={{marginTop: 'var(--container-margin)'}} pagination={false} />
        </Card>
      </div>
    </Modal>
  )
}

export default CandidateView;
